"use client";

import React, { useState, useEffect, useRef, useCallback } from "react";
import Link from "next/link";
import { LeftOutlined, EditOutlined, HomeOutlined } from "@ant-design/icons";
import { Card, Button, List, Avatar, Typography, Space, Modal, Pagination } from "antd";
import { useRouter } from "next/navigation";
import api from "../../utils/api";
import { useUser } from "../../context/userContext";
import styles from "@/components/Font.module.css";

const { Title, Text } = Typography;

// 用户类型定义
interface User {
  id: string;
  username: string;
  email: string;
  display_name: string;
  bio: string;
  role: string;
  icon: string;
  access_token: string;
  password?: string;
}

// 帖子类型定义
interface Post {
  id: string;
  title: string;
  content: string;
  authorId: string;
  likes: number;
  views: number;
  favourites: number;
  createdAt: string;
  authorDisplayName?: string;
}

// 评论类型定义
interface Comment {
  id: string;
  postId: string;
  content: string;
  likes: number;
  createdAt: string;
}

// 列表项样式
const listItemStyle = {
  border: "1px solid #e8e8e8",
  borderRadius: 8,
  padding: 16,
  marginBottom: 16,
  transition: "box-shadow 0.3s",
  cursor: "pointer",
  ":hover": {
    boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
  },
};

// 加载中状态样式
const loadingStyle = {
  display: "flex",
  justifyContent: "center",
  padding: "16px 0",
  color: "#7A6E6E",
};

export default function ProfilePage() {
  const [loading, setLoading] = useState(true);
  const [initialLoading, setInitialLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("posts");
  const [userPosts, setUserPosts] = useState<Post[]>([]);
  const [userComments, setUserComments] = useState<Comment[]>([]);
  const [likedComments, setLikedComments] = useState<Comment[]>([]);
  const [likedOrSavedPosts, setLikedOrSavedPosts] = useState<Post[]>([]);
  const [userName, setUserName] = useState("");
  const [userDisplayName, setUserDisplayName] = useState("");
  const [showLogoutModal, setShowLogoutModal] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(4);
  const [total, setTotal] = useState(0);
  const [avatarUrl, setAvatarUrl] = useState("");
  const [isLoadingMore, setIsLoadingMore] = useState(false); // 控制是否正在加载更多
  const router = useRouter();
  const { user } = useUser();
  const contentRef = useRef<HTMLDivElement>(null); // 内容区域引用，用于滚动监听

  useEffect(() => {
    if (!user || !user.access_token) {
      router.push("/login");
      return;
    }
    setAvatarUrl(user.icon || "");
    setUserName(user.username || "");
    setUserDisplayName(user.display_name);
    fetchData();
    
    // 初始加载完成
    setInitialLoading(false);
  }, [user, router, activeTab]);

  // 获取用户的帖子、评论、点赞和收藏数据
  const fetchData = async (isMore = false) => {
    try {
      if (isLoadingMore) return; // 如果正在加载更多，不重复请求
      
      setIsLoadingMore(true);
      let url;
      let params = {
        page: String(isMore ? page + 1 : page),
        pageSize: String(pageSize),
      };

      // 根据 activeTab 设置不同的 URL 和参数
      switch (activeTab) {
        case "posts":
          url = "/posts/author";
          params = {
            ...params,
            authorId: user.id,
          };
          break;

        case "comments":
          url = "/comments/user";
          params = {
            ...params,
            uerId: user.id, // 注意：保留原始参数名拼写错误
          };
          break;

        case "likedComments":
          url = "/comments/like";
          params = {
            ...params,
            uerId: user.id, // 注意：保留原始参数名拼写错误
          };
          break;

        case "likes":
          url = "/posts/like";
          break;

        case "saves":
          url = "/posts/favourites";
          break;

        default:
          break;
      }

      const headers = {
        Authorization: `Bearer ${user.access_token}`,
        "Content-Type": "application/json",
      };
      const response = await api.get(url, { params, headers });

      if (response.status === 200) {
        switch (activeTab) {
          case "posts":
            const postsData = Array.isArray(response.data.posts)
              ? response.data.posts
              : [];
            const totalCount = response.data.total || 0;
            const postsWithDisplayName = await Promise.all(
              postsData.map(async (post: Post) => {
                try {
                  const userResponse = await api.get("/users/info", {
                    params: { id: post.authorId },
                  });
                  return {
                    ...post,
                    authorDisplayName:
                      userResponse.data?.display_name || "未知作者",
                  };
                } catch (error) {
                  console.error(`获取作者 ${post.authorId} 信息失败:`, error);
                  return {
                    ...post,
                    authorDisplayName: "未知作者",
                  };
                }
              })
            );
            
            // 加载更多时合并数据，否则替换数据
            setUserPosts(isMore ? [...userPosts, ...postsWithDisplayName] : postsWithDisplayName);
            setTotal(totalCount);
            break;
          case "comments":
            const commentsData = Array.isArray(response.data.comments)
              ? response.data.comments
              : [];
            setUserComments(isMore ? [...userComments, ...commentsData] : commentsData);
            setTotal(response.data.total || 0);
            break;
          case "likedComments":
            const likedCommentsData = Array.isArray(response.data.comments)
              ? response.data.comments
              : [];
            setLikedComments(isMore ? [...likedComments, ...likedCommentsData] : likedCommentsData);
            setTotal(response.data.total || 0);
            break;
          case "likes":
          case "saves":
            const data = Array.isArray(response.data.posts || response.data)
              ? (response.data.posts || response.data) as Post[]
              : [];
            const totalCountLikedOrSaved = response.data.total || 0;
            const dataWithDisplayName = await Promise.all(
              data.map(async (post: Post) => {
                try {
                  const userResponse = await api.get("/users/info", {
                    params: { id: post.authorId },
                  });
                  return {
                    ...post,
                    authorDisplayName:
                      userResponse.data?.display_name || "未知作者",
                  };
                } catch (error) {
                  console.error(`获取作者 ${post.authorId} 信息失败:`, error);
                  return {
                    ...post,
                    authorDisplayName: "未知作者",
                  };
                }
              })
            );
            
            setLikedOrSavedPosts(isMore ? [...likedOrSavedPosts, ...dataWithDisplayName] : dataWithDisplayName);
            setTotal(totalCountLikedOrSaved);
            break;
          default:
            break;
        }
        
        // 加载更多时更新页码
        if (isMore) {
          setPage(prev => prev + 1);
        }
      }
    } catch (error) {
      console.error("数据获取失败:", error);
    } finally {
      setLoading(false);
      setIsLoadingMore(false);
    }
  };

  // 处理编辑个人资料按钮点击事件
  const handleEditProfile = () => {
    router.push(`/profile/${userName}/edit`);
  };

  // 处理返回主页按钮点击事件
  const handleBackToHomepage = () => {
    router.back(); // 直接返回上一个页面
  };

  // 处理退出登录按钮点击事件
  const handleLogout = () => {
    setShowLogoutModal(true);
  };

  // 处理确认退出登录
  const confirmLogout = () => {
    router.push("/");
    setShowLogoutModal(false);
  };

  // 处理取消退出登录
  const cancelLogout = () => {
    setShowLogoutModal(false);
  };

  // 渲染帖子卡片
  const renderPostCard = (post: Post) => {
    return (
      <Link href={`/posts/${post.id}`} passHref prefetch>
        <div
          style={{
            ...listItemStyle,
            backgroundColor: "white",
            borderRadius: 12,
            boxShadow: "0 2px 8px rgba(0, 0, 0, 0.09)",
            transition: "all 0.3s ease"
          }}
          className="hover:shadow-lg hover:-translate-y-1"
        >
          <Title level={4} style={{ margin: "0 0 8px 0", fontSize: 16, color: "#333" }}>
            {post.title}
          </Title>
          <Text
            type="secondary"
            style={{ marginBottom: 8, fontSize: 12, color: "#7A6E6E" }}
          >
            作者：{post.authorDisplayName}
          </Text>
          <Text
            style={{
              marginBottom: 12,
              color: "#666",
              lineHeight: 1.5,
              fontSize: 14,
              display: "-webkit-box",
              "-webkit-line-clamp": 3,
              "-webkit-box-orient": "vertical",
              overflow: "hidden",
            }}
          >
            {post.content}
          </Text>
          <Space style={{ marginTop: "auto" }}>
            <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
              <span style={{ display: "flex", alignItems: "center" }}>
                <span>{post.likes}</span>
                <span style={{ marginLeft: 5 }}>👍</span>
              </span>
            </Button>
            <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
              <span style={{ display: "flex", alignItems: "center" }}>
                <span>{post.views}</span>
                <span style={{ marginLeft: 5 }}>👀</span>
              </span>
            </Button>
            <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
              <span style={{ display: "flex", alignItems: "center" }}>
                <span>{post.favourites}</span>
                <span style={{ marginLeft: 5 }}>⭐</span>
              </span>
            </Button>
          </Space>
          <Text
            type="secondary"
            style={{
              marginTop: 8,
              fontSize: 10,
              color: "#999",
            }}
          >
            {post.createdAt}
          </Text>
        </div>
      </Link>
    );
  };

  // 渲染加载更多指示器
  const renderLoadingIndicator = () => {
    if (isLoadingMore) {
      return (
        <div style={loadingStyle}>
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[#D6A7A1] mr-2"></div>
          <span>加载更多内容...</span>
        </div>
      );
    }
    
    // 已加载全部内容
    if ((activeTab === "posts" && userPosts.length >= total) || 
        (activeTab === "comments" && userComments.length >= total) ||
        (activeTab === "likedComments" && likedComments.length >= total) ||
        (activeTab === "likes" || activeTab === "saves" && likedOrSavedPosts.length >= total)) {
      return (
        <div style={{ ...loadingStyle, color: "#999" }}>
          <span>已经到底啦</span>
        </div>
      );
    }
    
    return null;
  };

  // 渲染不同标签页的内容
  const renderTabContent = () => {
    switch (activeTab) {
      case "posts":
        return (
          <div ref={contentRef}>
            {/* 帖子列表 - 移除了分页选择器，只保留滚动加载 */}
            <List
              itemLayout="horizontal"
              dataSource={userPosts}
              renderItem={(item: Post) => (
                <Link href={`/posts/${item.id}`} passHref prefetch>
                  <List.Item
                    style={{
                      ...listItemStyle,
                      backgroundColor: "white",
                      borderRadius: 12,
                      boxShadow: "0 2px 8px rgba(0, 0, 0, 0.09)",
                      transition: "all 0.3s ease"
                    }}
                    className="hover:shadow-lg hover:-translate-y-1"
                  >
                    <div style={{ flex: 1 }}>
                      <Title level={4} style={{ margin: "0 0 8px 0", fontSize: 16, color: "#333" }}>
                        {item.title}
                      </Title>
                      <Text
                        type="secondary"
                        style={{ marginBottom: 8, fontSize: 12, color: "#7A6E6E" }}
                      >
                        作者：{item.authorDisplayName}
                      </Text>
                      <Text
                        style={{
                          marginBottom: 12,
                          color: "#666",
                          lineHeight: 1.5,
                          fontSize: 14,
                          display: "-webkit-box",
                          "-webkit-line-clamp": 3,
                          "-webkit-box-orient": "vertical",
                          overflow: "hidden",
                        }}
                      >
                        {item.content}
                      </Text>
                      <Space style={{ marginTop: "auto" }}>
                        <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                          <span style={{ display: "flex", alignItems: "center" }}>
                            <span>{item.likes}</span>
                            <span style={{ marginLeft: 5 }}>👍</span>
                          </span>
                        </Button>
                        <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                          <span style={{ display: "flex", alignItems: "center" }}>
                            <span>{item.views}</span>
                            <span style={{ marginLeft: 5 }}>👀</span>
                          </span>
                        </Button>
                        <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                          <span style={{ display: "flex", alignItems: "center" }}>
                            <span>{item.favourites}</span>
                            <span style={{ marginLeft: 5 }}>⭐</span>
                          </span>
                        </Button>
                      </Space>
                      <Text
                        type="secondary"
                        style={{
                          marginTop: 8,
                          fontSize: 10,
                          color: "#999",
                        }}
                      >
                        {item.createdAt}
                      </Text>
                    </div>
                  </List.Item>
                </Link>
              )}
            />
            
            {/* 加载更多指示器 */}
            {renderLoadingIndicator()}
          </div>
        );

      case "comments":
        return (
          <div ref={contentRef}>
            <List
              itemLayout="horizontal"
              dataSource={userComments}
              renderItem={(item: Comment) => (
                <Link href={`/posts/${item.postId}`} passHref prefetch>
                  <List.Item
                    actions={[
                      <Button type="text" style={{ color: "#666" }}>
                        <span style={{ display: "flex", alignItems: "center" }}>
                          <span>{item.likes}</span>
                          <span style={{ marginLeft: 5 }}>👍</span>
                        </span>
                      </Button>,
                    ]}
                    style={{
                      ...listItemStyle,
                      backgroundColor: "white",
                      borderRadius: 12,
                      boxShadow: "0 2px 8px rgba(0, 0, 0, 0.09)",
                      transition: "all 0.3s ease"
                    }}
                    className="hover:shadow-lg hover:-translate-y-1"
                  >
                    <List.Item.Meta
                      title={
                        <Text
                          style={{
                            color: "#333",
                            fontSize: 16,
                            fontWeight: "bold",
                          }}
                        >
                          {item.content}
                        </Text>
                      }
                    />
                    <div
                      style={{ color: "#999", fontSize: "12px", marginTop: 8 }}
                    >
                      {item.createdAt}
                    </div>
                  </List.Item>
                </Link>
              )}
            />
            
            {/* 加载更多指示器 */}
            {renderLoadingIndicator()}
          </div>
        );

      case "likedComments":
        return (
          <div ref={contentRef}>
            <List
              itemLayout="horizontal"
              dataSource={likedComments}
              renderItem={(item: Comment) => (
                <Link href={`/posts/${item.postId}`} passHref prefetch>
                  <List.Item
                    actions={[
                      <Button type="text" style={{ color: "#666" }}>
                        <span style={{ display: "flex", alignItems: "center" }}>
                          <span>{item.likes}</span>
                          <span style={{ marginLeft: 5 }}>👍</span>
                        </span>
                      </Button>,
                    ]}
                    style={{
                      ...listItemStyle,
                      backgroundColor: "white",
                      borderRadius: 12,
                      boxShadow: "0 2px 8px rgba(0, 0, 0, 0.09)",
                      transition: "all 0.3s ease"
                    }}
                    className="hover:shadow-lg hover:-translate-y-1"
                  >
                    <List.Item.Meta
                      title={
                        <Text
                          style={{
                            color: "#333",
                            fontSize: 16,
                            fontWeight: "bold",
                          }}
                        >
                          {item.content}
                        </Text>
                      }
                    />
                    <div
                      style={{ color: "#999", fontSize: "12px", marginTop: 8 }}
                    >
                      {item.createdAt}
                    </div>
                  </List.Item>
                </Link>
              )}
            />
            
            {/* 加载更多指示器 */}
            {renderLoadingIndicator()}
          </div>
        );

      case "likes":
      case "saves":
        return (
          <div ref={contentRef}>
            <List
              itemLayout="horizontal"
              dataSource={likedOrSavedPosts}
              renderItem={(item: Post) => (
                <Link href={`/posts/${item.id}`} passHref prefetch>
                  <List.Item
                    style={{
                      ...listItemStyle,
                      backgroundColor: "white",
                      borderRadius: 12,
                      boxShadow: "0 2px 8px rgba(0, 0, 0, 0.09)",
                      transition: "all 0.3s ease"
                    }}
                    className="hover:shadow-lg hover:-translate-y-1"
                  >
                    <div style={{ flex: 1 }}>
                      <Title level={4} style={{ margin: "0 0 8px 0", fontSize: 16, color: "#333" }}>
                        {item.title}
                      </Title>
                      <Text
                        type="secondary"
                        style={{ marginBottom: 8, fontSize: 12, color: "#7A6E6E" }}
                      >
                        作者：{item.authorDisplayName}
                      </Text>
                      <Text
                        style={{
                          marginBottom: 12,
                          color: "#666",
                          lineHeight: 1.5,
                          fontSize: 14,
                          display: "-webkit-box",
                          "-webkit-line-clamp": 3,
                          "-webkit-box-orient": "vertical",
                          overflow: "hidden",
                        }}
                      >
                        {item.content}
                      </Text>
                      <Space style={{ marginTop: "auto" }}>
                        <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                          <span style={{ display: "flex", alignItems: "center" }}>
                            <span>{item.likes}</span>
                            <span style={{ marginLeft: 5 }}>👍</span>
                          </span>
                        </Button>
                        <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                          <span style={{ display: "flex", alignItems: "center" }}>
                            <span>{item.views}</span>
                            <span style={{ marginLeft: 5 }}>👀</span>
                          </span>
                        </Button>
                        <Button type="text" style={{ color: "#666", padding: 0, fontSize: 12 }}>
                          <span style={{ display: "flex", alignItems: "center" }}>
                            <span>{item.favourites}</span>
                            <span style={{ marginLeft: 5 }}>⭐</span>
                          </span>
                        </Button>
                      </Space>
                      <Text
                        type="secondary"
                        style={{
                          marginTop: 8,
                          fontSize: 10,
                          color: "#999",
                        }}
                      >
                        {item.createdAt}
                      </Text>
                    </div>
                  </List.Item>
                </Link>
              )}
            />
            
            {/* 加载更多指示器 */}
            {renderLoadingIndicator()}
          </div>
        );
      default:
        return null;
    }
  };

  // 滚动事件处理 - 当用户滚动到距离底部一定距离时加载更多
  const handleScroll = useCallback(() => {
    if (isLoadingMore) return;
    
    const contentElement = contentRef.current;
    if (!contentElement) return;
    
    const { scrollTop, scrollHeight, clientHeight } = contentElement;
    const dataLength = 
      activeTab === "posts" ? userPosts.length : 
      activeTab === "comments" ? userComments.length : 
      activeTab === "likedComments" ? likedComments.length : 
      likedOrSavedPosts.length;
    
    // 当滚动到距离底部100px时加载更多
    if (scrollTop + clientHeight >= scrollHeight - 100 && dataLength < total) {
      fetchData(true);
    }
  }, [isLoadingMore, total, activeTab, userPosts.length, userComments.length, likedComments.length, likedOrSavedPosts.length]);

  // 组件挂载和卸载时的滚动事件监听
  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.addEventListener("scroll", handleScroll);
    }
    
    return () => {
      if (contentRef.current) {
        contentRef.current.removeEventListener("scroll", handleScroll);
      }
    };
  }, [handleScroll]);

  // 标签页切换时重置页码和数据
  useEffect(() => {
    setPage(1);
    setUserPosts([]);
    setUserComments([]);
    setLikedComments([]);
    setLikedOrSavedPosts([]);
    fetchData();
  }, [activeTab]);

  if (initialLoading) {
    return (
      <div 
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
          backgroundColor: "#F4EDEB"
        }}
      >
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-[#D6A7A1] mb-4"></div>
          <p className="text-[#7A6E6E] text-lg">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        backgroundColor: "#F4EDEB",
        color: "#333333",
        minHeight: "100vh",
        padding: "20px",
      }}
    >
      {/* 页面顶部操作栏 主页图标 + 返回图标 + 退出登录*/}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          width: "100%",
          maxWidth: "1200px",
          padding: "0 16px",
          boxSizing: "border-box",
          zIndex: 10,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {/* 左侧主页图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s"
            }}
            onClick={() => router.push("/homepage/home")}
            className="hover:text-[#D6A7A1]"
          >
            <HomeOutlined />
          </div>

          {/* 左侧返回图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s"
            }}
            onClick={handleBackToHomepage}
            className="hover:text-[#D6A7A1]"
          >
            <LeftOutlined />
          </div>
        </div>

        {/* 右侧退出登录 */}
        <div
          style={{
            color: "#7A6E6E",
            textDecoration: "underline",
            cursor: "pointer",
            fontSize: 16,
            transition: "color 0.3s"
          }}
          onClick={handleLogout}
          className="hover:text-[#D6A7A1]"
        >
          退出登录
        </div>
      </div>

      <Modal
        title="确认退出"
        open={showLogoutModal}
        onCancel={cancelLogout}
        onOk={confirmLogout}
        okText="确认"
        cancelText="取消"
        okButtonProps={{ 
          className: "bg-[#D6A7A1] hover:bg-[#C19A8C] text-white font-medium rounded-full px-6 py-2 transition-all shadow-md hover:shadow-lg" 
        }}
        cancelButtonProps={{ 
          className: "bg-white border border-[#D6A7A1] text-[#D6A7A1] hover:bg-[#F4EDEB] font-medium rounded-full px-6 py-2 transition-all shadow-md hover:shadow-lg" 
        }}
      >
        <p style={{ color: "#7A6E6E" }}>确定要退出登录吗？</p>
      </Modal>

      <Card
        style={{
          width: "90%",
          maxWidth: 1100,
          background: "white",
          border: "none",
          borderRadius: 20,
          margin: "20px auto",
          boxShadow: "0 4px 20px rgba(0, 0, 0, 0.08)",
          overflow: "hidden",
          display: "flex",
          flexDirection: "column",
          position: "relative" // 确保z-index生效
        }}
        title={
          <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap" }}>
            {/* 用户头像 */}
            <Avatar
              src={`http://120.26.138.4:3000${avatarUrl}`}
              size={100}
              style={{
                margin: 16,
                boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
                border: "4px solid white",
                borderRadius: "50%",
              }}
            />
            {/* 用户名和简介 */}
            <div style={{ marginLeft: 16, flex: 1, minWidth: 200 }}>
              <p
                style={{
                  margin: 0,
                  color: "#333",
                  fontWeight: "bold",
                  fontSize: "24px",
                }}
              >
                {userDisplayName}
              </p>
              <p style={{ margin: "8px 0 0 0", color: "#7A6E6E", fontSize: "16px" }}>
                {user.bio}
              </p>
            </div>
          </div>
        }
        extra={
          <Button
            onClick={handleEditProfile}
            style={{
              backgroundColor: "#D6A7A1",
              color: "white",
              border: "none",
              borderRadius: 20,
              padding: "8px 20px",
              boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
              transition: "all 0.3s",
              fontSize: 14,
              fontWeight: "medium"
            }}
            className="hover:bg-[#C19A8C] hover:shadow-md"
          >
            <EditOutlined /> 修改资料
          </Button>
        }
      >
        {/* 固定的菜单标签 */}
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            marginBottom: 16,
            borderBottom: "1px solid #eee",
            paddingBottom: 12,
            backgroundColor: "white", // 确保背景色与卡片一致
            position: "sticky", // 固定在顶部
            top: 0, // 相对于卡片顶部
            zIndex: 10, // 确保在内容之上
          }}
        >
          <Button
            type="text"
            onClick={() => setActiveTab("posts")}
            style={{
              color: activeTab === "posts" ? "#D6A7A1" : "#7A6E6E",
              margin: "0 10px",
              fontSize: 16,
              fontWeight: activeTab === "posts" ? "bold" : "normal",
              padding: "8px 16px",
              transition: "all 0.3s",
              borderRadius: 20,
            }}
            className={activeTab === "posts" ? "bg-[#F4EDEB]" : ""}
          >
            帖子
          </Button>
          <Button
            type="text"
            onClick={() => setActiveTab("comments")}
            style={{
              color: activeTab === "comments" ? "#D6A7A1" : "#7A6E6E",
              margin: "0 10px",
              fontSize: 16,
              fontWeight: activeTab === "comments" ? "bold" : "normal",
              padding: "8px 16px",
              transition: "all 0.3s",
              borderRadius: 20,
            }}
            className={activeTab === "comments" ? "bg-[#F4EDEB]" : ""}
          >
            评论
          </Button>
          <Button
            type="text"
            onClick={() => setActiveTab("likedComments")}
            style={{
              color: activeTab === "likedComments" ? "#D6A7A1" : "#7A6E6E",
              margin: "0 10px",
              fontSize: 16,
              fontWeight: activeTab === "likedComments" ? "bold" : "normal",
              padding: "8px 16px",
              transition: "all 0.3s",
              borderRadius: 20,
            }}
            className={activeTab === "likedComments" ? "bg-[#F4EDEB]" : ""}
          >
            点赞评论
          </Button>
          <Button
            type="text"
            onClick={() => setActiveTab("likes")}
            style={{
              color: activeTab === "likes" ? "#D6A7A1" : "#7A6E6E",
              margin: "0 10px",
              fontSize: 16,
              fontWeight: activeTab === "likes" ? "bold" : "normal",
              padding: "8px 16px",
              transition: "all 0.3s",
              borderRadius: 20,
            }}
            className={activeTab === "likes" ? "bg-[#F4EDEB]" : ""}
          >
            点赞帖子
          </Button>
          <Button
            type="text"
            onClick={() => setActiveTab("saves")}
            style={{
              color: activeTab === "saves" ? "#D6A7A1" : "#7A6E6E",
              margin: "0 10px",
              fontSize: 16,
              fontWeight: activeTab === "saves" ? "bold" : "normal",
              padding: "8px 16px",
              transition: "all 0.3s",
              borderRadius: 20,
            }}
            className={activeTab === "saves" ? "bg-[#F4EDEB]" : ""}
          >
            收藏
          </Button>
        </div>

        {/* 内容区域 - 设置为可滚动 */}
        <div 
          style={{
            flex: 1,
            overflow: "auto",
            maxHeight: "calc(100vh - 350px)", // 设置最大高度，防止内容溢出
            padding: "0 20px 20px", // 底部padding为加载指示器留出空间
          }}
        >
          {renderTabContent()}
        </div>
      </Card>
    </div>
  );
}    